<template>
	<view class="content">
		<u-tabs-swiper ref="hTabs"
			:is-scroll="false"
			:list="tablist" 
			:current="current" 
			@change="tabsChange"
			swiperWidth="750">
		</u-tabs-swiper>
		<u-tabs
			v-if="current == 2"
			:is-scroll="false"
			:list="chtablist" 
			:height="60"
			:font-size="24"
			:current="chcurrent" 
			@change="chtabsChange"
			swiperWidth="750">
		</u-tabs>
		<!-- swiper必须设置height:100%，因为swiper有默认的高度，只有设置高度100%才可以铺满页面  -->
		<swiper class="swiper" :current="swiperCurrent" @transition="transition" @animationfinish="animationfinish">
			<swiper-item class="swiper-item" v-for="(item, index) in comTabsList" :key="index">
				{{item.name}}
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tablist: [{
					name: 'tab1'
				},{
					name: 'tab2'
				},{
					name: 'tab3'
				}],
				chtablist: [{
					name: 'item1'
				},{
					name: 'item2'
				},{
					name: 'item3'
				}],
				current: 0,
				chcurrent: 0,
				swiperCurrent: 0
			}
		},
		computed: {
			comTabsList(){
				let list = [...this.chtablist];
				list.splice(0, 1);   //因为item1和tab3是重叠的，所以不需要item1这个页面
				return [...this.tablist, ...list]; //这是swiper-item用来循环的list
			}
		},
		methods: {
			
			/**tabs通知swiper切换*/
			tabsChange(index) {
				this.swiperCurrent = index;
			},
			
			chtabsChange(index){
				//这里子类tabs需要在点击项获取index的时候+2
				//由于tab都是从0开始计算，但是swiper现在不可能是第0项, 也就是要加上前面滑走的数量(下标0开始算)
				this.swiperCurrent = index + 2;
			},
			
			/**swiper-item左右移动，通知tabs的滑块跟随移动*/
			transition(e) {
				let dx = e.detail.dx;
				if(this.swiperCurrent < 2){
					//必须在swiper的滑动范围在 0 - 2 之间才对父级tab的bar进行滑动效果
					this.$refs.hTabs.setDx(dx);
				}
			},
			
			/**swiper滑动结束，分别设置tabs和swiper的状态*/
			animationfinish(e) {
				let current = e.detail.current;
				this.$refs.hTabs.setFinishCurrent(current);
				if(current > 2){ //如果swiper当前下标大于2，说明现在应该改变的是子tab
					this.chcurrent = current - 2;
				}else if(current == 2){  //如果等于2，说明现在在tab3, 那么tab3以及item1都应该选中
					this.chcurrent = 0;
					this.current = current;
				}else{  //如果小于2 那么说明现在父级tab需要向左移动
					this.current = current;
				}
				this.swiperCurrent = current;  //swiper一直在移动
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content{
		height: calc(100vh - 80px);
		.swiper{
			height: 100%;
		}
	}
</style>
